const qcloud = require('./vendor/qcloud-weapp-client-sdk/index.js')
var tipCont = {
  '211': '工号已被其他人绑定',
  '212': '工号或姓名不正确'
}
// 补零处理
function zeroize(value) {
  return value < 9 ? `0${value}` : value
}

// 时间处理
function GetDateStr(times) {
  var dd = new Date();
  var afferentDate = new Date(times);
  
  if (
      dd.getFullYear() != afferentDate.getFullYear || 
      dd.getMonth() != afferentDate.getMonth() || 
      (dd.getDate() - afferentDate.getDate() >=2) 
      ) 
  {
    return [`${zeroize(afferentDate.getMonth() + 1)}月${zeroize(afferentDate.getDate())}`, `${zeroize(afferentDate.getHours())}:${zeroize(afferentDate.getMinutes())}`]
  } else {
    var iarr = ['今天', '昨天']
    var index = dd.getDate() - afferentDate.getDate()

    return [iarr[index], `${afferentDate.getHours()}:${afferentDate.getMinutes()}`]
  }
}

// 接口处理
function ajaxFn({ url, method = 'POST', callback, body = {}, header = {  'content-type': 'application/x-www-form-urlencoded'} }){
  if(url == '') {
    console.error('请传入有效的请求地址');
    return false;
  }

  if (typeof callback !== 'function') {
    console.error('callback传入的不是一个有效函数');
    return false;
  }

  qcloud.request({
    url: url,
    method: method,
    header: header,
    login: true,
    data: body,
    success: (response) => {
      var data = response.data
      if (data.code === 202) {
        wx.navigateTo({
          url: '/pages/login/login'
        })
      } else if (data.code === 0) {
        callback(data)
      } else {
        if (!!tipCont[data.code]) {
          wx.showToast({
            title: tipCont[data.code],
            image: "../../images/error.png",
            icon: 'none',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '糟糕，网线又被谁拔掉了！',
            image: "../../images/error.png",
            icon: 'none',
            duration: 2000
          })
        }
        
      }
    },
    fail: (err) => {
      wx.showToast({
        title: '请求错误！',
        image: "../../images/error.png",
        icon: 'none',
        duration: 2000
      })
    }
  });
}

// 时间处理推算前一天
function formatDate(time, number) {
  
  var times = number * 24 * 60 * 60 * 1000
  var preDate = new Date(new Date(time).getTime() - times)

  return `${preDate.getFullYear()}-${zeroize(preDate.getMonth() + 1)}-${zeroize(preDate.getDate())} 00:00:00`
};


// 聚合参数
var obj = {
  GetDateStr,
  zeroize,
  ajaxFn,
  formatDate
}

module.exports = obj;